<template>
  <span class="dispatch-kanban1-list">
    <el-container style="padding-top: 10px">
      <el-main ref="main">
        <el-table border style="width: 100%" :data="tableData">
          <el-table-column prop="date" :label="nowtime" width="200px">
            <el-table-column
              class="table-column"
              prop="date"
              label="项目"
              width="150"
              left="48px"
            >
              <el-table-column prop="lx" label="品位" width="120">
              </el-table-column>
            </el-table-column>
          </el-table-column>
          <el-table-column label="在线品位看板" class="common-form-dlg">
            <!--                                    <el-table-column label="总尾" center="true" prop="zw" :show-overflow-tooltip="true"></el-table-column>-->
            <el-table-column
              label="混尾"
              center="true"
              prop="hw"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="锌尾"
              center="true"
              prop="xw"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="原矿"
              center="true"
              prop="yk"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="半优先"
              center="true"
              prop="byx"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="铜锌分原"
              center="true"
              prop="txfy"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="铜尾"
              center="true"
              prop="tw"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="总铜精矿"
              center="true"
              prop="ztjk"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="锌精矿"
              center="true"
              prop="xjk"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="浮铜精矿"
              center="true"
              prop="ftjk"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="柱铜精矿"
              center="true"
              prop="zhtjk"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="20">
            <div class="selectForm">
              <el-form
                :inline="true"
                :model="queryForm"
                size="mini"
                style="margin-top: 20px"
              >
                <el-form-item label="样品">
                  <el-select v-model="id" placeholder="样品" clearable multiple>
                    <el-option
                      v-for="item in findYplx"
                      :key="item.streamId"
                      :label="item.streamName"
                      :value="item.streamId"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="开始结束时间">
                  <el-date-picker
                    v-model="selectTime"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    align="right"
                    style="width: 450px; height: 29px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="querySubmit"
                    >查询</el-button
                  > </el-form-item
                ><el-form-item>
                  <el-button type="primary" @click="derived"
                    >导出表格</el-button
                  >
                </el-form-item>
                <!-- <el-form-item>
                  <el-button type="primary" @click="test">测试</el-button>
                </el-form-item> -->
              </el-form>
            </div>
            <div id="dayMineHandleLine" style="height: 500px"></div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </span>
</template>

<style lang="scss">
.el-table thead.is-group tr:first-of-type th:first-of-type {
  background-color: #e5e5e5;
}
.el-table thead.is-group tr:first-of-type {
  background-color: #f6f6f6;
}

.el-table thead.is-group tr:first-of-type th:nth-of-type(2) {
  text-align: center;
}
.el-table thead.is-group tr:nth-of-type(2) th:first-of-type {
  text-align: right;
}

.el-table thead.is-group th {
  background: none;
}
.el-table thead.is-group tr:nth-of-type(2) th:first-of-type {
  border-bottom: none;
}
.el-table thead.is-group tr:nth-of-type(2) th:first-of-type:before {
  content: '';
  position: absolute;
  width: 1px;
  height: 80px; /*这里需要自己调整，根据td的宽度和高度*/
  top: 0;
  left: 0;
  background-color: grey;
  opacity: 0.3;
  display: block;
  transform: rotate(-60deg); /*这里需要自己调整，根据线的位置*/
  transform-origin: top;
}
.el-table thead.is-group tr:last-of-type th:first-of-type:before {
  content: '';
  position: absolute;
  width: 1px;
  height: 75px; /*这里需要自己调整，根据td的宽度和高度*/
  bottom: 0;
  right: 0;
  background-color: grey;
  opacity: 0.3;
  display: block;
  transform: rotate(-62deg); /*这里需要自己调整，根据线的位置*/
  transform-origin: bottom;
  // background:red;
}
</style>

<script>
import * as echarts from 'echarts';
// import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import * as $http from '@/api/server/http';
export default {
  name: 'planManageList',
  components: {},
  computed: {
    tableHead1() {
      if (this.resArr.length > 0) {
        return this.resArr.map((i) => i.streamName);
      }
    },
    tableHead2() {
      if (this.series.length > 0) {
        return this.series.map((i) => i.name);
      }
    },
    colunm1() {
      if (this.cupwDate.length > 0) {
        return this.cupwDate;
      }
    },
    colunm2() {
      if (this.series.length > 0) {
        return this.series.map((i) => i.data);
      }
    },
  },
  data() {
    return {
      derivedArr: [], //导出数据数组
      series: [], //折线图数据
      resArr: [], //后端返回数据
      testArr: [],
      legend: [], //图例数组
      selectTime: [],
      pickerOptions: {
        //大于当前月分的日期不可选
        disabledDate: (time) => {
          return (
            time.getTime() < Date.now() - 3600 * 1000 * 24 * 183 ||
            time.getTime() > Date.now()
          );
        },
      },
      queryForm: {
        streamId: '',
      },
      id: [], //下拉框选项
      findYplx: [],
      nowtime: '',

      activeName: 'first',
      tableHeight: '',
      tableData: [
        { taste: 'Cu(%)' },
        { taste: 'Zn(%)' },
        { taste: 'Fe(%)' },
        { taste: '流量' },
        { taste: '时间' },
      ],
      dayMineHandleLine: '', //铜品位实时曲线
      cupwtitle: '总尾样品实时曲线数据分析',
      cupwDate: [], //时间
      cupwseries: '',
      znpwseries: '',
      interval: '',
      iStime: '',
      iStime1: '',
    };
  },
  created() {
    this.curkbOnlinePWKB1(); //表格
    this.getFindYplx(); //下拉框的值
    // this.OnlinePWKB1();
    var date1 = new Date();
    this.selectTime[1] =
      date1.getFullYear() +
      '-' +
      (date1.getMonth() + 1) +
      '-' +
      date1.getDate() +
      ' ' +
      date1.getHours() +
      ':' +
      date1.getMinutes() +
      ':' +
      date1.getSeconds(); //time1表示当前时间
    this.iStime =
      date1.getFullYear() +
      '-' +
      (date1.getMonth() + 1) +
      '-' +
      date1.getDate();
    this.iStime1 =
      date1.getFullYear() +
      '-' +
      (date1.getMonth() + 1) +
      '-' +
      (date1.getDate() - 1);
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() - 3);
    this.selectTime[0] =
      date2.getFullYear() +
      '-' +
      (date2.getMonth() + 1) +
      '-' +
      date2.getDate() +
      ' ' +
      date1.getHours() +
      ':' +
      date1.getMinutes() +
      ':' +
      date1.getSeconds();
  },
  mounted() {
    this.calcHeight();
    this.querySubmit();
  },
  methods: {
    // test() {
    //   console.log('多选框id', this.id);
    //   console.log('时间', this.colunm1);
    //   console.log('数据', this.colunm2);
    //   console.log('表头', this.tableHead2);
    //   console.log('导出的excel数据', this.derivedArr);
    // },
    //导出
    derived() {
      if (this.resArr.length == 0) {
        this.$message.error('请先点击查询得出图表结果后导出');
        return;
      }

      this.colunm2.forEach((data, idx) => {
        data.forEach((d, idx1) => {
          if (!this.derivedArr[idx1]) {
            this.derivedArr[idx1] = {};
          }
          this.derivedArr[idx1][this.tableHead2[idx]] = d;
        });
      });
      this.derivedArr.forEach((i, id) => {
        i['时间'] = this.colunm1[id];
      });
      console.log('表', this.derivedArr);

      // 从JS对象数组创建工作表
      const ws = XLSX.utils.json_to_sheet(this.derivedArr);
      // 列属性对象的数组，设置每列的列宽，10代表10个字符，注意中文占2个字符
      ws['!cols'] = [];
      // 创建一个新的工作簿
      const wb = XLSX.utils.book_new();
      // 将工作表附加到工作簿 (工作簿, 工作表, sheet命名)
      XLSX.utils.book_append_sheet(wb, ws, '数据详情');
      // 尝试写入和保存 XLSX 文件(工作簿, xlsx文件名称)
      XLSX.writeFile(wb, '列表详情.xlsx');
    },
    replace: function (input) {
      let reg = new RegExp('\u3002', 'g');
      var inputs = input.replace(reg, '<br/>');
      return inputs;
    },
    querySubmit() {
      this.legend = []; //每次请求清除原有的标题数组
      //清除折线图之前的数据
      if (this.dayMineHandleLine) {
        this.dayMineHandleLine.clear();
      }
      if (this.id.length > 0) {
        let paramsArr = this.id.map((i) => {
          return {
            streamId: i,
            begin: this.selectTime[0],
            end: this.selectTime[1],
          };
        });
        console.log('传参数组', paramsArr);

        //多个传参请求
        Promise.all(paramsArr.map((i) => $http.getChart(i)))
          .then((res) => {
            this.resArr = res.map((i) => i.data); //结果集数组， 里面的item是一个对象（包含cu zn time）
            console.log('多个请求的数据返回集', this.resArr);
            let { time, Cu } = this.resArr[0];
            this.cupwDate = time;
            this.interval = Math.ceil(Cu.length / 15);
            this.testArr = this.resArr.map((i) => {
              this.legend.push(`${i.streamName || '暂无数据'}Cu`);
              this.legend.push(`${i.streamName || '暂无数据'}Zn`);

              let arr = [
                {
                  name: `${i.streamName}Cu`,
                  type: 'line',
                  data: i.Cu,
                  markLine: {
                    data: [{ type: 'average', name: '平均值' }],
                    lineStyle: {
                      width: 3, //设置线条粗细
                    },
                  },
                },
                {
                  name: `${i.streamName}Zn`,
                  type: 'line',
                  data: i.Zn,
                  markLine: {
                    data: [{ type: 'average', name: '平均值' }],
                    lineStyle: {
                      width: 3, //设置线条粗细
                    },
                  },
                },
              ];
              return arr;
            });
            let seriesArr = this.testArr.flat(Infinity);
            this.series = seriesArr;
            console.log('图标Y轴数据', this.series);
            console.log('图列数据', this.legend);
            this.initChart();
          })
          .catch((err) => {
            this.$message.error(err);
          });
      }
    },

    initChart() {
      this.dayMineHandleLine = echarts.init(
        document.getElementById('dayMineHandleLine')
      );
      this.dayMineHandleLine.setOption({
        title: {
          text: this.cupwtitle,
          y: 'top',
          x: 'center',
          textStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          top: '10%',
          data: this.legend,
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '',
          top: '10%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          name: 'x:时间',
          nameLocation: 'start',
          boundaryGap: false,
          data: this.cupwDate,
          axisLabel: {
            interval: this.interval,
            interale: 0,
            rotate: 50,
          },
        },
        yAxis: {
          type: 'value',
          name: 'y:品位',
        },
        series: this.series,
      });
    },

    calcHeight() {
      this.tableHeight = this.$refs.main.$el.offsetHeight - 67 + 'px';
    },

    async curkbOnlinePWKB1() {
      const result = await $http.getXmsData();
      console.log('网络请求的结果', result);
      const { data, code } = result;
      if (code == 0) {
        this.tableData = data;
      }
      this.tableData[0].lx = '时间';
      this.tableData[1].lx = 'Cu(%)';
      this.tableData[2].lx = 'Zn(%)';
      this.tableData[3].lx = 'Fe(%)';
      this.tableData[4].lx = '流量';
    },

    // getParams(id) {
    //   if (this.selectTime == null) {
    //     this.selectTime = [];
    //   }
    //   let params = {
    //     streamId: id,
    //     begin: this.selectTime[0],
    //     end: this.selectTime[1],
    //   };
    //   return params;
    // },
    // async OnlinePWKB1(v) {
    //   const result = await $http.getChart(v);
    //   const { data, code } = result;
    //   if (code == 0) {
    //     return data;
    //   }
    // },
    async getFindYplx() {
      const result = await $http.getStreams();
      const { data, code } = result;
      if (code == 0) {
        this.findYplx = data;
        console.log('下拉框', this.findYplx);
        this.id.push(data[0].streamId);
      }
    },
  },
};
</script>
